package com.gxuwz.medical.web.servlet.menu;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.MenuDao;
import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.menu.Menu;
import com.gxuwz.medical.tools.ResponseUtil;
import com.gxuwz.medical.tools.StringUtil;

import net.sf.json.JSONObject;

public class MenuModifyServlet extends HttpServlet {

	DbUtil dbUtil = new DbUtil();
	MenuDao menuDao = new MenuDao();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		saveMenu(request, response);
		System.out.println("来到了菜单保存");
	}

	private void saveMenu(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		Menu menu = null;
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String pid = request.getParameter("pid");
		String url = request.getParameter("url");

		System.out.println("id=" + id + "name=" + name + "pid=" + pid + "url=" + url);
		try {

			menu = new Menu(id, name, pid, url);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (!StringUtil.isEmpty(id)) {
			menu.setId(id);
		}
		Connection con = null;
		try {
			con = dbUtil.getCon();
			int saveNums = 0;
			JSONObject result = new JSONObject();
			if (!StringUtil.isEmpty(id)) {
				saveNums = menuDao.menuModify(con, menu);
				System.out.print("更改菜单数量为" + saveNums);
			} else {
				saveNums = menuDao.menuAdd(con, menu);
				System.out.print("增加菜单数量为" + saveNums);
			}
			if (saveNums > 0) {
				result.put("success", "true");
			} else {
				result.put("success", "true");
				result.put("errorMsg", "保存失败");
			}
			ResponseUtil.write(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
